<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分组数据 树状结构-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入分组名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--店员数据-->
      <el-col :span="20" :xs="24">
        <!-- 搜索条件 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="店员昵称" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入店员昵称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="登录账户" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入登录账户"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="店员等级" prop="userLevel">
            <el-select
              v-model="queryParams.userLevel"
              placeholder="店员等级"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in levelList"
                :key="dict.levelId"
                :label="dict.levelTitle"
                :value="dict.levelId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="激活状态" prop="active">
            <el-select
              v-model="queryParams.active"
              placeholder="店员激活状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="在线状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="店员在线状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.app_employee_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="自动接单" prop="autoOrder">
            <el-select
              v-model="queryParams.autoOrder"
              placeholder="店员是否自动接单"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="是否实名" prop="isRealName">
            <el-select
              v-model="queryParams.isRealName"
              placeholder="店员是否实名"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="动态审核" prop="isDynamicAudit">
            <el-select
              v-model="queryParams.isDynamicAudit"
              placeholder="店员动态是否审核"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="店员性别" prop="sex">
            <el-select
              v-model="queryParams.sex"
              placeholder="店员性别"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="服务项目" prop="serviceType">
            <el-cascader
              :options="projectOptions"
              @change="handleServiceChange"
              :props="{ multiple: false, checkStrictly: true }"
              clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="店员地址" prop="address">
            <el-input
              v-model="queryParams.address"
              placeholder="请输入店员地址"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
            <el-input
              v-model="queryParams.shopId"
              placeholder="请输入店铺ID"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮组 -->
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['employee:user:add']"
            >新增</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['employee:user:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['employee:user:remove']"
            >删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['employee:user:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['employee:user:export']"
            >导出</el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <template>
          <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" label="序号" width="50" align="center" />
            <!-- <el-table-column label="店员ID" align="center" key="userId" prop="userId" /> -->
            <el-table-column label="店员" align="center" key="nickName" min-width="180" >
              <template slot-scope="scope">
                <div class="flex-align-center">
                  <el-avatar shape="circle" size="medium" :src="scope.row.avatar" alt="404"></el-avatar>
                  <div class="mgl5 font-14">{{scope.row.nickName}}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="在线状态" align="center" key="status" prop="status">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.app_employee_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="等级" align="center" key="userLevel" prop="userLevel" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.levelInfo.levelTitle }}</span>
              </template>
            </el-table-column>
            <el-table-column label="平均评分" align="center" key="score" prop="score" sortable="custom" :sort-orders="['descending', 'ascending']" width="130"/>
            <el-table-column label="评分总分" align="center" key="scoreTotal" prop="scoreTotal" sortable="custom" :sort-orders="['descending', 'ascending']" width="130"/>
            <el-table-column label="人气排序" align="center" key="userSort" prop="userSort" width="120" sortable="custom" :sort-orders="['descending', 'ascending']"/>
            <el-table-column label="登录账户" align="center" key="userName" prop="userName" width="120" />
            <el-table-column label="地址" align="center" key="address" prop="address" width="250" />
            <el-table-column label="生日" align="center" key="birthday" prop="birthday" width="120" sortable="custom" :sort-orders="['descending', 'ascending']" />
            <el-table-column label="性别" align="center" key="sex" prop="sex">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
              </template>
            </el-table-column>
            <el-table-column label="激活状态" align="center" key="active" prop="active">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.active"/>
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" prop="shopInfo.shopName" min-width="120" v-if="$store.getters && $store.getters.admin" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" width="160" sortable="custom" :sort-orders="['descending', 'ascending']">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="160"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['employee:user:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['employee:user:remove']"
                >删除</el-button>
                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['employee:user:resetPwd', 'employee:user:edit']">
                  <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                      v-hasPermi="['employee:user:resetPwd']">重置密码</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </template>
      </el-col>
    </el-row>

    <!-- 添加或修改店员配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="height:600px; overflow-y: scroll;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="店员昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入店员昵称" maxlength="10" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="店员头像" prop="avatar">
              <el-input v-model="form.avatar" placeholder="图片地址" class="mgb10" v-if="$store.getters && $store.getters.admin"/>
              <ImageUpload v-model="form.avatar" :limit="1" :file-size="2" :file-type="['png', 'jpg', 'jpeg', 'gif']" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="介绍视频" prop="speech">
              <el-input v-model="form.speech" placeholder="图片地址" class="mgb10" v-if="$store.getters && $store.getters.admin"/>
              <FileUpload v-model="form.speech" :limit="1" :file-size="2" :fileType="['mp4', 'avi', 'rmvb', 'mov', 'hevc']" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.speech">
            <el-form-item label="预览">
              <video width="150" height="150" controls>
                <source :src="speechStr" type="video/mp4">
                您的浏览器不支持 video 标签。
              </video>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="店员相册" prop="images">
              <el-input v-model="form.images" placeholder="图片地址" class="mgb10" type="textarea" :autosize="{ minRows: 2, maxRows: 10}" v-if="$store.getters && $store.getters.admin"/>
              <ImageUpload v-model="form.images" :file-size="2" :file-type="['png', 'jpg', 'jpeg', 'gif']" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="归属分组" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属分组" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区编码" prop="addressCode">
              <el-cascader v-model="form.addressCode" :options="areaList" @change="handleChangeAddress" placeholder="地区编码" maxlength="20" style="width: 230px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="登录账户" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入登录账户" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="微信ID" prop="wxId">
              <el-input v-model="form.wxId" placeholder="请输入微信ID" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="form.birthday" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间" style="width: 230px"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="人气排序" prop="userSort">
              <el-input v-model="form.userSort" placeholder="请输入人气排序" type="number" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总分" prop="scoreTotal">
              <el-input v-model="form.scoreTotal" placeholder="请输入人气排序" type="number" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平均评分" prop="score">
              <el-input v-model="form.score" placeholder="请输入平均评分" type="number" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务项目" prop="serviceType">
              <el-checkbox v-model="projectExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
              <el-checkbox v-model="projectNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
              <el-checkbox v-model="projectConnect" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
              <el-tree
                class="tree-border"
                :data="projectOptions"
                show-checkbox
                default-expand-all
                ref="projectRefs"
                node-key="id"
                :check-strictly="!form.projectCheckStrictly"
                empty-text="加载中，请稍候"
                :props="defaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="店员标签" prop="tags">
              <el-select v-model="form.tags" multiple filterable allow-create
                default-first-option  placeholder="请选择店员标签，可创建条目" class="width-100">
                <el-option v-for="item in tagsList" 
                :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="等级" prop="userLevel">
              <el-select v-model="form.userLevel" placeholder="请选择等级">
                <el-option
                  v-for="dict in levelList"
                  :key="dict.levelId"
                  :label="dict.levelTitle"
                  :value="dict.levelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="店员性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="动态需要审核" prop="isDynamicAudit">
              <el-radio-group v-model="form.isDynamicAudit">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="8">
            <el-form-item label="自动接单" prop="autoOrder">
              <el-radio-group v-model="form.autoOrder">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="激活状态" prop="active">
              <el-radio-group v-model="form.active">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="在线状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.app_employee_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新人列表展示" prop="isNewShow">
              <el-radio-group v-model="form.isNewShow">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="自我介绍" prop="userProfile">
              <el-input v-model="form.userProfile" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 店员导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的店员数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, deptTreeSelect } from "@/api/employee/user";
import { projectTreeSelect } from "@/api/market/project";
import { listLevel } from "@/api/market/level";
import { getToken } from "@/utils/auth";
import addressData from "@/utils/area/area.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "EmployeeUser",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'sys_yes_no', 'app_employee_status'],
  components: { Treeselect },
  data() {
    var validateTreeProject = (rule, value, callback) => {
      let arr = this.$refs.projectRefs.getCheckedKeys(); // 在此获取选中的树形数据
      if (arr.length == 0 || !arr) {
        callback(new Error("请选择服务项目"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店员表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 分组树选项
      deptOptions: undefined,
      
      projectExpand: true,
      projectNodeAll: false,
      projectConnect: false,
      // 服务项目
      projectOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分组名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 店员导入参数
      upload: {
        // 是否显示弹出层（店员导入）
        open: false,
        // 弹出层标题（店员导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的店员数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/employee/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        wxId: undefined,
        phonenumber: undefined,
        status: undefined,
        active: undefined,
        sex: undefined,
        addressCode: undefined,
        userLevel: undefined,
        serviceType: undefined,
        isRealName: undefined,
        isDynamicAudit: undefined,
        isNewShow: undefined,
        autoOrder: undefined,
        shopId: undefined,
        deptId: undefined
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "店员登录账户不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '店员登录账户长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "店员昵称不能为空", trigger: "blur" },
          { min: 1, max: 10, message: '店员昵称长度必须介于 1 和 10 之间', trigger: 'blur' }
        ],
        // userSort: [
        //   { required: true, message: "店员排序不能为空", trigger: "blur" }
        // ],
        score: [
          { required: true, message: "店员评分分数不能为空", trigger: "blur" }
        ],
        userProfile: [
          { required: true, message: "店员介绍不能为空", trigger: "blur" }
        ],
        serviceType: [
          { required: true, validator: validateTreeProject, trigger: "change" }
        ],
        userLevel: [
          { required: true, message: "店员等级不能为空", trigger: "blur" }
        ],
        tags: [
          { required: true, message: "店员标签不能为空", trigger: "blur" }
        ],
        birthday: [
          { required: true, message: "店员生日不能为空", trigger: "blur" }
        ],
        addressCode: [
          { required: true, message: "店员地区编码不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "店员头像不能为空", trigger: "blur" }
        ],
        images: [
          { required: true, message: "店员相册不能为空", trigger: "blur" }
        ],
        speech: [
          { required: true, message: "店员声音文件不能为空", trigger: "blur" }
        ],
        wxId: [
          { required: true, message: "微信号不能为空", trigger: "blur" }
        ],
        password: [
          // { required: true, message: "店员密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '店员密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          { required: true, message: "店员手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      areaList:[],
      tagsList:[],
      levelList:[],
      speechStr: '',
      baseUrl: process.env.VUE_APP_BASE_API,
      filePre: "http",
    };
  },
  watch: {
    // 根据名称筛选分组树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    'form.speech'(val){
      this.speechStr = val && val.indexOf(this.baseUrl) === -1 && val.indexOf(this.filePre) === -1 ? process.env.VUE_APP_BASE_API + val : val
    }
  },
  created() {
    this.areaList = addressData
    Promise.all([this.getLevelList()]).then((values) => {
        this.getList();
      });
    this.getDeptTree();
    this.getProjectTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询店员列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询等级列表 */
    getLevelList() {
      let that = this;
      return new Promise((resolve, reject)=>{
        listLevel(this.addDateRange({ pageNum: 1, pageSize: 10000, orderByColumn: 'levelSort', isAsc: 'ascending',}, null)).then(response => {
          that.levelList = response.rows;
          resolve(that.levelList)
        });
      })
    },
    /** 查询分组下拉树结构 - 部门 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询分组下拉树结构 - 服务类型 */
    getProjectTree() {
      projectTreeSelect().then(response => {
        this.projectOptions = response.data;
        if(this.projectOptions.length){
          this.projectOptions.forEach(e => {
            e.value = e.id
            if(e.children){
              e.children.forEach(e1 => {
                e1.value = e1.id
                if(e1.children){
                  e1.children.forEach(e2 => {
                    e2.value = e2.id
                  });
                }
              });
            }
          });
          console.log(this.projectOptions)
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.projectRefs != undefined) {
        this.$refs.projectRefs.setCheckedKeys([]);
      }
      this.projectExpand = true
      this.projectNodeAll = false
      this.projectConnect = false
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        userLevel: undefined,
        autoOrder: "N",
        isDynamicAudit: "N",
        isNewShow: "Y",
        serviceType: [],
        email: undefined,
        sex: "0",
        status: "0",
        active: "0",
        remark: undefined,
        userProfile: undefined,
        postIds: [],
        roleIds: [],
        projectCheckStrictly: true,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then(response => {
        this.open = true;
        this.title = "添加店员";
        this.form.password = this.initPassword;
      });
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.form.serviceType = this.form.serviceType ? this.form.serviceType.split(",") : []
        this.form.addressCode = this.form.addressCode ? this.form.addressCode.split(",") : []
        this.form.tags = this.form.tags ? this.form.tags.split(",") : []
        this.$set(this.form, "postIds", response.postIds);
        this.$set(this.form, "roleIds", response.roleIds);
        this.$nextTick(() => {
          this.$refs.projectRefs.setCheckedKeys(this.form.serviceType);
        });
        this.open = true;
        this.title = "修改店员";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入账户"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "店员密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.serviceType = this.getProjectAllCheckedKeys();
          let params = JSON.parse(JSON.stringify(this.form))
          params.serviceType = params.serviceType && params.serviceType.length ? params.serviceType.join(',') : ''
          params.addressCode = params.addressCode && params.addressCode.length ? params.addressCode.join(',') : ''
          params.tags = params.tags && params.tags.length ? params.tags.join(',') : ''
          if(params.birthday){
            let b_a = params.birthday.split('-')
            params.constellation = this.getAstro(b_a[1], b_a[2])
          }
          if (this.form.userId != undefined) {
            updateUser(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除店员编号为"' + userIds + '"的数据项？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('employee/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "店员导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('employee/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 根据生日的月份和日期，计算星座。
    getAstro(m,d){
      let s = "摩羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手摩羯"; 
      let arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]; 
      let start = m * 2 - (d < arr[m - 1] ? 2 : 0); 
      return s.substring(start, start + 2) + "座"; 
    },
    handleServiceChange(e){
      console.log(e)
      if(e.length){
        this.queryParams.serviceType = e[e.length - 1]
      }else{
        this.queryParams.serviceType = undefined
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.projectOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.projectRefs.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.projectRefs.setCheckedNodes(value ? this.projectOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.projectCheckStrictly = value ? true: false;
    },
    // 所有服务项目节点数据
    getProjectAllCheckedKeys() {
      // 目前被选中的服务项目节点
      let checkedKeys = this.$refs.projectRefs.getCheckedKeys();
      // 半选中的服务项目节点
      let halfCheckedKeys = this.$refs.projectRefs.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    handleChangeAddress(p){
      let result = ''
      this.areaList.forEach(v=>{
        if(v.value === p[0]){
          result = v.label
        }
        v.children.forEach(c_v=>{
          if(c_v.value === p[1]){
            result = result +'-' + c_v.label
          }
          c_v.children.forEach(c_c_v=>{
            if(c_c_v.value === p[2]){
              result = result + '-' + c_c_v.label
            }
          })
        })
      })
      this.form.address = result
    }
  }
};
</script>